package com.inossem.allotin.utils.requestUtils;


import com.inossem.allotin.utils.ToastUtils;
import com.inossem.wms.vo.BaseBean;

import java.lang.reflect.UndeclaredThrowableException;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 自定义Callback
 *
 * @author 詹建宇
 * @time on 2018/11/15 16:15
 * @email jianyu.zhan@inossem.com
 */
public abstract class InossemCallback<T extends BaseBean> implements Callback<T> {

    public abstract void success(Response<T> response);

    public abstract void failure(Response<T> response);

    @Override
    public void onResponse(Call<T> call, Response<T> response) {
        if (response.isSuccessful()) {
            if (null != response.body() && null != response.body().getHead() && null != response.body().getHead().getError_code()&& null != response.body().getHead().getStatus()) {
                if ("0".equals(response.body().getHead().getError_code())&&"true".equals(response.body().getHead().getStatus())){
                    success(response);
                }else {
                    failure(response);
                }
            } else {
                ToastUtils.showToast("返回数据错误");
            }
        } else {
            ToastUtils.showToast("请求错误: " + response.raw().toString());
        }
    }

    @Override
    public void onFailure(Call call, Throwable t) {
        ToastUtils.showToast(getErrorMessage(t));
//        Logger.e(getErrorMessage(t));
    }

    private String getErrorMessage(Throwable e) {
        String msg = null;
        if (e instanceof UndeclaredThrowableException) {
            Throwable targetEx = ((UndeclaredThrowableException) e).getUndeclaredThrowable();
            if (targetEx != null) {
                msg = targetEx.getMessage();
            }
        } else {
            msg = e.getMessage();
        }
        return msg;
    }

}
